package com.exp.controller;

import com.exp.dto.NoticeInfDTO;
import com.exp.dto.NoticePageQueryDTO;
import com.exp.interceptor.JwtTokenAdminInterceptor;
import com.exp.pojo.NoticeInf;
import com.exp.pojo.UserInf;
import com.exp.result.PageResult;
import com.exp.result.Result;
import com.exp.result.StatusCode;
import com.exp.service.NoticeInfService;
import com.exp.service.UserInfService;
import com.exp.utils.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 公告管理模块-pyz
 */
@RestController
@RequestMapping("/admin/noticeInf")
@Slf4j
public class NoticeInfController {

    @Autowired
    private NoticeInfService noticeInfService;

    /*
     * 公告查询-分页查询
     * 搜索条件：公告名称、公告内容
     */
    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody NoticePageQueryDTO noticePageQueryDTO){
        PageResult pageResult = noticeInfService.pageQuey(noticePageQueryDTO);
        return Result.success(StatusCode.SUCCESS, Message.PAGE_SUCCESS,pageResult);
    }

    /*
     * 修改公告
     * 输入：公告标题、公告内容
     */
    @PutMapping("/update")
    public Result<NoticeInf> update(@RequestBody NoticeInfDTO noticeInfDTO){
        log.info("编辑公告信息：{}", noticeInfDTO);
        noticeInfService.update(noticeInfDTO);
        System.out.println(noticeInfDTO);
        Integer noid = noticeInfDTO.getId();
        NoticeInf noticeInf = new NoticeInf();
        if (noid!=null){
            noticeInf = noticeInfService.getById(noid);
        }
        return Result.success(StatusCode.SUCCESS,Message.UPDATE_SUCCESS,noticeInf);
    }

    /*
     * 添加公告
     * 输入：公告标题、公告内容
     */

    @PostMapping("/add")
    public Result<NoticeInf> save(@RequestBody NoticeInfDTO noticeInfDTO){
        log.info("新增公告信息：{}", noticeInfDTO);
        NoticeInf noticeInf = new NoticeInf();
        BeanUtils.copyProperties(noticeInfDTO, noticeInf);
        // 从ThreadLocal中获取userId
        Integer userId = JwtTokenAdminInterceptor.threadLocal.get();
        if (userId != null) {
            // 使用userId进行操作
            noticeInf.setUserId(userId);
        }
        noticeInfService.save(noticeInf);
        return Result.success(StatusCode.SUCCESS,Message.SAVE_SUCCESS,noticeInf);
    }

    /*
    批量删除
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestParam List<Integer> ids) {
        noticeInfService.deleteBatch(ids);
        return Result.success(StatusCode.SUCCESS,Message.DELETE_SUCCESS,ids);
    }

    /*
     * 公告预览：公告标题、公告内容
     * 根据公告ID查询 公告内容和标题 并返回
     */
//    @GetMapping("/getById/{id}")
//    public Result<NoticeInf> getById(@PathVariable Integer id){
//        NoticeInf noticeInf = noticeInfService.getById(id);
//        return Result.success(StatusCode.SUCCESS,Message.SELECT_SUCCESS,noticeInf);
//    }

}
